package router

import (
	"blog/app/middleware"
	"blog/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func Router() *gin.Engine {
	router := gin.Default()

	// 静态资源
	router.Static("/static", "./static")

	router.GET("/", service.Hello)

	// 添加用户
	//router.GET("/add_user", service.AddUser)

	router.POST("/api/admin/login", service.LoginHandler)
	router.POST("/register", service.RegisterHandler)

	// 使用路由组和中间件进行鉴权
	auth := router.Group("/auth")
	auth.Use(middleware.JwtToken())
	{
		auth.GET("/user_list", service.GetUserList)
	}

	// 处理跨域问题
	cors := router.Group("/admin")
	cors.Use(middleware.Cors())
	{
		cors.GET("/users", service.GetUserList)
		cors.OPTIONS("/users", service.GetUserList)

		// 登录接口
		cors.POST("/login", service.LoginHandler)
		cors.OPTIONS("/login", service.LoginHandler)
	}

	// 兼容调试接口 personcard
	// http://localhost:5174/api/personcard/GetTags
	api := router.Group("/api")
	api.Use(middleware.Cors())
	{
		personCard := api.Group("/personcard")

		personCard.Any("/GetTags", service.GetTags)
		// http://localhost:5173/api/personcard/GetUserName
		personCard.Any("/GetUserName", service.GetUserName)
		personCard.Any("/GetUserListByAdminTags", service.GetUserListByAdminTags)

		accessauth := api.Group("/accessauth")
		accessauth.Any("/GetSpecialAuthApplyList", service.GetUserList)
	}

	err := router.Run(viper.GetString("server.httpPort"))
	if err != nil {
		fmt.Println("gin启动失败", err)
		return nil
	}
	return router
}
